'use client';

// 认证上下文
// REF: API-USER-0042@v1.0

import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { User } from '@/lib/api';
import { authApi, userApi } from '@/services/api';

interface AuthContextType {
  user: User | null;
  loading: boolean;
  login: (email: string, password: string) => Promise<{ success: boolean; message: string }>;
  logout: () => Promise<void>;
  refreshUser: () => Promise<void>;
  isAuthenticated: boolean;
  isAdmin: boolean;
  initialCheckDone: boolean;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [initialCheckDone, setInitialCheckDone] = useState(false);

  // 检查用户认证状态
  const checkAuth = async () => {
    try {
      // 确保在客户端环境中运行
      if (typeof window === 'undefined') {
        setLoading(false);
        setInitialCheckDone(true);
        return;
      }
      
      const token = localStorage.getItem('access_token');
      if (!token) {
        setLoading(false);
        setInitialCheckDone(true);
        return;
      }

      const response = await userApi.getCurrentUser();
      if (response.success && response.data) {
        setUser(response.data);
      } else {
        // Token无效，清除本地存储
        if (typeof window !== 'undefined') {
          localStorage.removeItem('access_token');
          localStorage.removeItem('refresh_token');
        }
      }
    } catch (error) {
      console.error('认证检查失败:', error);
      if (typeof window !== 'undefined') {
        localStorage.removeItem('access_token');
        localStorage.removeItem('refresh_token');
      }
    } finally {
      setLoading(false);
      setInitialCheckDone(true);
    }
  };

  // 用户登录
  const login = async (email: string, password: string) => {
    try {
      const response = await authApi.login({ email, password });
      
      if (response.success && response.data) {
        const { access_token, refresh_token, user: userData } = response.data;
        
        // 保存token到本地存储
        if (typeof window !== 'undefined') {
          localStorage.setItem('access_token', access_token);
          localStorage.setItem('refresh_token', refresh_token);
        }
        
        // 更新用户状态
        setUser(userData);
        
        // 刷新用户信息以获取最新的登录时间
        await refreshUser();
        
        return { success: true, message: '登录成功' };
      } else {
        return { success: false, message: response.message || '登录失败' };
      }
    } catch (error: any) {
      console.error('登录失败:', error);
      return { 
        success: false, 
        message: error.response?.data?.message || '网络错误，请稍后重试' 
      };
    }
  };

  // 用户登出
  const logout = async () => {
    try {
      await authApi.logout();
    } catch (error) {
      console.error('登出请求失败:', error);
    } finally {
      // 清除本地存储和用户状态
      if (typeof window !== 'undefined') {
        localStorage.removeItem('access_token');
        localStorage.removeItem('refresh_token');
      }
      setUser(null);
    }
  };

  // 刷新用户信息
  const refreshUser = async () => {
    try {
      const response = await userApi.getCurrentUser();
      if (response.success && response.data) {
        setUser(response.data);
      }
    } catch (error) {
      console.error('刷新用户信息失败:', error);
    }
  };

  // 组件挂载时检查认证状态
  useEffect(() => {
    checkAuth();
  }, []);

  const value: AuthContextType = {
    user,
    loading,
    login,
    logout,
    refreshUser,
    isAuthenticated: !!user,
    isAdmin: user?.role === 'admin',
    initialCheckDone
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};